package com.cdc.statusbar;

import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.WindowManager;

import java.lang.reflect.Field;

public class GetStatusBarHeightActivity extends AppCompatActivity {

    private ViewGroup bar_layout ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_getstabar_height);
        setStatus();
    }

    /**
     * 系统版本4.4或以上才可以设置沉浸式状态栏
     *
     * 设置沉浸式状态栏
     */
    private void setStatus(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //设置状态栏透明
          getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //设置导航栏透明
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

            bar_layout = (ViewGroup) findViewById(R.id.bar_layout);
            final int statusBarHeight = getStatusBarHeight();
            bar_layout.post(new Runnable() {
                @Override
                public void run() {
                    int height = bar_layout.getHeight();
                    ViewGroup.LayoutParams layoutParams = bar_layout.getLayoutParams();

                    layoutParams.height = statusBarHeight + height ;
                    bar_layout.setLayoutParams(layoutParams);
                }
            });
        }
    }


    /**
     * 获取状态栏的高度
     * @return
     */
    protected int getStatusBarHeight(){

        try {
            //通过反射获取到类
            Class<?> aClass = Class.forName("com.android.internal.R$dimen");
            //创建对象
            Object o = aClass.newInstance();
            //拿去属性
            Field status_bar_height = aClass.getField("status_bar_height");
            //获取值
            Object o1 = status_bar_height.get(o);
            int height = Integer.parseInt(o1.toString());
            //
            return getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0 ;
    }
}
